package com.b511.swpu.cementbackend.service.impl;

import com.b511.swpu.cementbackend.service.WellBoreStructureService;
import com.b511.swpu.cementbackend.dto.input.BoreholeConditionInputDto;
import com.b511.swpu.cementbackend.entity.WellBoreStructure;
import com.b511.swpu.cementbackend.exception.CementException;
import com.b511.swpu.cementbackend.repository.WellBoreStructureRepository;
import com.b511.swpu.cementbackend.util.*;
import com.b511.swpu.cementbackend.util.enumeration.Code;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.JoinType;
import java.util.Optional;

@Service
public class WellBoreStructureServiceImpl implements WellBoreStructureService {

    private final WellBoreStructureRepository wellBoreStructureRepository;

    public WellBoreStructureServiceImpl(WellBoreStructureRepository wellBoreStructureRepository) {
        this.wellBoreStructureRepository = wellBoreStructureRepository;
    }

    @Override
    public R getWellBoreStructureByCondition(BoreholeConditionInputDto boreholeConditionInputDto, PageRequest pageRequest) {
        return R.ok().putData(wellBoreStructureRepository.findAll((Specification<WellBoreStructure>) (root, cq, cb)
                -> Help.createPredicate(boreholeConditionInputDto, root.join("borehole", JoinType.LEFT), cb), pageRequest));
    }

    @Override
    @Transactional
    public R updateWellBoreStructure(Long id, WellBoreStructure updateWellBoreStructure) {
        Optional<WellBoreStructure> optionalWellBoreStructure = wellBoreStructureRepository.findById(id);
        if (!optionalWellBoreStructure.isPresent()) {
            throw new CementException(Code.SELECT_FAIL);
        }
        WellBoreStructure wellBoreStructure = optionalWellBoreStructure.get();
        CopyUtil.copyProperties(updateWellBoreStructure, wellBoreStructure);
        wellBoreStructureRepository.save(wellBoreStructure);
        return R.ok();
    }
}
